//
//  RootWebViewController.m
//  YouYiKuProject
//
//  Created by xue on 2018/11/29.
//  Copyright © 2018年 xuezi. All rights reserved.
//

#import "RootWebViewController.h"
#import "GCWebviewJSBridge.h"
#import "WXApiRequestHandler.h"
#import "WXApiManager.h"
#import "WechatAuthSDK.h"
#import "UIAlertView+WX.h"
#import "APOrderInfo.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APRSASigner.h"
#import "UIImageView+WebCache.h"
#import "AppDelegate.h"
#import "WxPayModel.h"
#import <AVFoundation/AVFoundation.h>
#import "WXApi.h"
#import "WXAuth.h"
#import "WXSpeech.h"
#import "NativeAlbum.h"
#import "AVAudio.h"

#define ssRGBHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]



@interface RootWebViewController ()<UIWebViewDelegate,UIActionSheetDelegate,WXApiManagerDelegate,UITextViewDelegate, WechatAuthAPIDelegate,WXApiDelegate,WXAuthDelegate,AVAudioRecorderDelegate,NativeAlbumDelegate,WXSpeechDelegate,AVAudioDelegate>

@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) GCWebviewJSBridge *bridge;


@property (nonatomic, strong) NSURL * urlPlay;
@property (nonatomic, strong) AVAudioRecorder *recorder;
@property (nonatomic, strong) GCWVJSBResponseCallback responseCallback_WXpay;
@property (nonatomic, strong) GCWVJSBResponseCallback responseCallback_Alipay;
@property (nonatomic, strong) GCWVJSBResponseCallback responseCallback_Video;
@property (nonatomic, strong) GCWVJSBResponseCallback responseCallback_WXlogin;

@property (nonatomic, strong) NSString * numPhoto;
@property (nonatomic, strong) NSString * cover;



@end

@implementation RootWebViewController

- (void)initRecorder{
    
    AVAudioSession * session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [session setActive:YES error:nil];
    //录音设置
    NSMutableDictionary * recordSetting = [[NSMutableDictionary alloc]init];
    //设置录音格式
    [recordSetting  setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
    //设置录音采样率（HZ）
    [recordSetting setValue:[NSNumber numberWithFloat:11025.0] forKey:AVSampleRateKey];
    //录音通道数
    [recordSetting setValue:[NSNumber  numberWithInt:2] forKey:AVNumberOfChannelsKey];
    //线性采样位数
    [recordSetting  setValue:[NSNumber numberWithInt:8] forKey:AVLinearPCMBitDepthKey];
    //录音的质量
    [recordSetting  setValue:[NSNumber numberWithInt:AVAudioQualityHigh] forKey:AVEncoderAudioQualityKey];
    //获取沙盒路径 作为存储录音文件的路径
    NSString * strUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSLog(@"path = %@",strUrl);
    //创建url
    NSURL * url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/123.caf",strUrl]];
    self.urlPlay = url;
    NSError * error ;
    //初始化AVAudioRecorder
    self.recorder = [[AVAudioRecorder alloc]initWithURL:url settings:recordSetting error:&error];
    //开启音量监测
    self.recorder.meteringEnabled = YES;
    self.recorder.delegate = self;
    if(error){
        NSLog(@"创建录音对象时发生错误，错误信息：%@",error.localizedDescription);
    }
}
//设置状态栏颜色
- (void)setStatusBarBackgroundColor:(UIColor *)color {
    
    UIView *statusBar = [[[UIApplication sharedApplication] valueForKey:@"statusBarWindow"] valueForKey:@"statusBar"];
    if ([statusBar respondsToSelector:@selector(setBackgroundColor:)]) {
        statusBar.backgroundColor = color;
    }
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    ///修改状态栏颜色
//    [self setStatusBarBackgroundColor:ssRGBHex(0x87E1D5)];
    [self setStatusBarBackgroundColor:[UIColor blackColor]];
    
    // 1.新建WebView
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    self.webView.backgroundColor = [UIColor whiteColor];
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:self.webView];
    
    // 2.加载网页
//    NSString * htmlPath = [[NSBundle mainBundle] pathForResource:@"index1" ofType:@"html"];
//    NSString * htmlString = [NSString stringWithContentsOfFile:htmlPath encoding:NSUTF8StringEncoding error:nil];
//    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] resourcePath]];
//    [self.webView loadHTMLString:htmlString baseURL:baseURL];



    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"default/index.html" relativeToURL:[[NSBundle mainBundle] bundleURL]]]];
    

    
    // 3.开启日志
    [GCWebviewJSBridge setEnableLogging];
    
    // 4.给webView建立JS和OC的沟通桥梁
    _bridge = [GCWebviewJSBridge bridgeForWebView:self.webView];
    [_bridge setwebViewDelegate:self];
    
    
    /* JS调用OC的API:访问相册 */
    [_bridge registerObjCHandler:@"openNativeAlbum" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        NSLog(@"需要%@图片   %@", data[@"maxNum"], data);
        self.numPhoto =data[@"maxNum"];
//        if (self.cover.length==0) {
            self.cover =data[@"cover"];

//        }else{
//            if (![self.cover isEqualToString:data[@"cover"]]) {
//                self.cover =data[@"cover"];
//
//                if ([NativeAlbum sharedInstance].zdxArray.count>0) {
//                    [[NativeAlbum sharedInstance].zdxArray removeAllObjects];
//                }
//
//            }
//        }
        [NativeAlbum sharedInstance].maxNum = [self.numPhoto integerValue];

        [[NativeAlbum sharedInstance] getPicImageList:self];
        [NativeAlbum sharedInstance].delegate =self;
        
    }];
    
    
    
    /* JS调用OC的API:访问本地视频 */
    [_bridge registerObjCHandler:@"openNativeVideo" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        
        self.responseCallback_Video = responseCallback;

        [[NativeAlbum sharedInstance] getVideoList:self];
        [NativeAlbum sharedInstance].delegate =self;
    }];
    
    ////支付
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiAlipayResult:) name:@"AlipayResult" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notiWXpayResult:) name:@"WXpayResult" object:nil];
    
    ///微信支付
    [WXApiManager sharedManager].delegate = self;
    /* JS调用OC的微信 支付宝 支付 */
    [_bridge registerObjCHandler:@"openNativePay" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        NSLog(@"微信支付参数js调用oc传入的参数%@", data);
        
        NSDictionary *dic =data;
        NSString *type =dic[@"type"];
        NSString *orderId =dic[@"orderId"];
        if ([type isEqualToString:@"1"]) {//微信
            AppDelegate * application = [[AppDelegate alloc]init];
            application.payType = 1;
            
            self.responseCallback_WXpay = responseCallback;
            [self getWXOrderDetailDataWithOrderId:orderId];
        }else if ([type isEqualToString:@"2"]){//支付宝
            AppDelegate * application = [[AppDelegate alloc]init];
            application.payType =2;
            
            self.responseCallback_Alipay = responseCallback;
            [self getOrderDetailDataWithOrderId:orderId];
        }
        
    
    }];
    
    /*  JS 调用微信授权登录*/
    [_bridge registerObjCHandler:@"wechatLogin" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        
        self.responseCallback_WXlogin = responseCallback;
        [WXAUTH sendWXAuthReq];
        [WXAuth sharedInstance].delegate =self;
    }];
    
    
    /*  JS 调用微信语音识别*/
    [_bridge registerObjCHandler:@"weChatVoice" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        
        NSDictionary *dic =data;
        NSString *type =dic[@"type"];
        if ([type isEqualToString:@"start"]) {//语音识别开始
            
            [[WXSpeech sharedInstance] startRecord];
            [WXSpeech sharedInstance].delegate =self;
            
        }else{//语音识别结束
            
            [[WXSpeech sharedInstance] finishRecorder1];
        }
        
    }];
    
    
        [self initRecorder];
    /*  JS 调用微信语音识别*/
    [_bridge registerObjCHandler:@"nativeRecord" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        
        self.responseCallback_Video = responseCallback;
        NSDictionary *dic =data;
        NSString *type =dic[@"type"];
        if ([type isEqualToString:@"start"]) {//录音开始


            [[AVAudio sharedInstance] startRecorder];
            [AVAudio sharedInstance].delegate =self;
        }else{//录音结束
            
            [[AVAudio sharedInstance] stopRecorder];

        }
        
        
    }];
    /*  JS 调用录音播放*/
    [_bridge registerObjCHandler:@"nativeRecord_paly" handler:^(id data, GCWVJSBResponseCallback responseCallback) {
        
        [[AVAudio sharedInstance] playSound];

    }];

    
}
- (void)creatAlert:(NSTimer *)timer{
    
    UIAlertController *alert = [timer userInfo];
    
    [alert dismissViewControllerAnimated:YES completion:nil];
    
    alert = nil;
    
    
}
    
/***微信支付结果 通知 返回支付结果给后台***/
-(void)notiWXpayResult:(NSNotification *)text{
    
    NSString *resultStatus =text.userInfo[@"resultStatus"];
    NSString *code =nil;
    NSString *message =text.userInfo[@"memo"];
    if ([resultStatus isEqualToString:@"0"]) {//支付成功
        code =@"1";//成功
    }else{
        code =@"0";//失败
    }
    NSDictionary *dic =@{
                         @"code":code,
                         @"message":message
                         };
    if (self.responseCallback_WXpay) {
        self.responseCallback_WXpay(dic);
    }
    
}
/***支付宝支付结果 通知 返回支付结果给后台***/
-(void)notiAlipayResult:(NSNotification *)text{
    
    NSString *resultStatus =text.userInfo[@"resultStatus"];
    NSString *code =nil;
    NSString *message =text.userInfo[@"memo"];
    if ([resultStatus isEqualToString:@"9000"]) {//支付成功
        code =@"1";//成功
    }else{
        code =@"0";//失败
    }
    NSDictionary *dic =@{
                         @"code":code,
                         @"message":message
                         };
    if (self.responseCallback_Alipay) {
        self.responseCallback_Alipay(dic);
    }

    
}


#pragma mark--UIWebViewDelegate
-(void)webViewDidStartLoad:(UIWebView *)webView{
    
}
-(void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitUserSelect='none';"];
    
    [self.webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout='none';"];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    NSLog(@"error==%@",error);
    // 被取消
    if([error code] == NSURLErrorCancelled)  {
        return;
    }
    
}

//
// 选中商品调用支付宝极简支付
//
#pragma mark -支付宝支付接口
-(void)getOrderDetailDataWithOrderId:(NSString*)orderId{
    
    [Utils POSTApliy:Url_W_AliPay_appPay parameters:@{@"orderId":orderId} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
       
    } success:^(id responseObject) {
        if (responseObject) {
            NSStringEncoding gbkEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
            NSString *payString = [[NSString alloc] initWithData:responseObject encoding:gbkEncoding];
            //version为@"\"xxx\"" ,在将字符串中\"替换为空即可
            payString = [payString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
         
            [self doAPPay:payString];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    

}
- (void)doAPPay:(NSString *)payString
{
    
    // NOTE: 如果加签成功，则继续执行支付
    if (payString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"youyikuproject";
        NSLog(@"1111%lu",(unsigned long)payString.length);
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:payString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);            
        }];
    }
}


#pragma mark -微信支付接口
//微信获取订单详情
-(void)getWXOrderDetailDataWithOrderId:(NSString*)orderId{
    
    [Utils POSTApliy:Url_WeChatPay parameters:@{@"orderId":orderId} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    } success:^(id responseObject) {
        if (responseObject) {
            
            NSDictionary * rootDic = [self returnDictionaryWithDataPath:responseObject];
            WxPayModel * model = [[WxPayModel alloc]init];
            model.appid = [rootDic objectForKey:@"appid"];
            model.noncestr = [rootDic objectForKey:@"noncestr"];
            model.package = [rootDic objectForKey:@"package"];
            model.partnerid = [rootDic objectForKey:@"partnerid"];
            model.prepayid = [rootDic objectForKey:@"prepayid"];
            model.sign = [rootDic objectForKey:@"sign"];
            model.timestamp = [rootDic objectForKey:@"timestamp"];
            
            
           NSString *str=[WXApiRequestHandler jumpToBizPay:model];
            if ([str isEqualToString:@"支付失败"]) {
                [Utils alertViewWithMessage:str];
            }
            
           
            
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
}
    
    // 微信支付返回结果回调
- (void)onResp:(BaseResp *)resp {
    if ([resp isKindOfClass:[PayResp class]]) {
        
        NSString *messega =nil;
        PayResp *response = (PayResp *)resp;
        switch (response.errCode) {
            case WXSuccess:
            messega =@"支付成功";
            break;
            case WXErrCodeUserCancel:
            messega =@"中途取消";
            break;
            default:{
                messega =@"支付失败";
            }
            
            break;
        }
        
     

        NSDictionary *dic =@{
                             @"message":messega
                             };
        if (self.responseCallback_WXpay) {
            self.responseCallback_WXpay(dic);
        }
    }
}

-(NSDictionary*)returnDictionaryWithDataPath:(NSData*)data
{
    NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    NSData * datas = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];
    
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:datas options:NSJSONReadingMutableLeaves error:nil];
    
    return jsonDict;
}


#pragma mark-WXAuthDelegate
//微信授权登录 code传给后台接口 返回的结果直接js返给后台
-(void)wXAuth:(WXAuth *)wXAuth wXUserInfo:(NSDictionary *)info{
    
    NSLog(@"info=%@",info);
    if (self.responseCallback_WXlogin) {
        self.responseCallback_WXlogin(info);
    }
}
#pragma mark--NativeAlbumDelegate
 -(void)nativeAlbumWarn:(NativeAlbum *)nativeAlbum{
     [self.bridge callHandler:@"warn2" data:nil responseCallback:^(id responseData) {
         
     }];
}
//选择本地相册 把图片上传接口 调用js方法storehouse返给后台
-(void)nativeAlbum:(NativeAlbum *)nativeAlbum nativeAlbumInfo:(NSDictionary *)info{
    NSLog(@"info=%@",info);
    
    
    if([self.cover isEqualToString:@"0"]){
        // 调用JS中的API
        [self.bridge callHandler:@"cover0" data:info responseCallback:^(id responseData) {
            
        }];
        
    }else if ([self.cover isEqualToString:@"1"]){
        // 调用JS中的API
        [self.bridge callHandler:@"cover1" data:info responseCallback:^(id responseData) {
            
        }];
    }else if ([self.cover isEqualToString:@"2"]){
        // 调用JS中的API
        [self.bridge callHandler:@"cover2" data:info responseCallback:^(id responseData) {
            
        }];
    }else if ([self.cover isEqualToString:@"4"]){
       
        // 调用JS中的API
        [self.bridge callHandler:@"leaf" data:info responseCallback:^(id responseData) {
            
        }];
    }
    else{
        
        // 调用JS中的API
        [self.bridge callHandler:@"storehouse" data:info responseCallback:^(id responseData) {
            
        }];
        
    }
   
}
//选择本地视频 把视频上传接口 返回的结果js调用videoupload
- (void)nativeAlbum:(NativeAlbum *)nativeAlbum nativeVidioInfo:(NSDictionary*)info{
    NSLog(@"info=%@",info);
   
    // 调用JS中的API
    [self.bridge callHandler:@"videoupload" data:info responseCallback:^(id responseData) {
        
    }];
}
#pragma mark--WXSpeechDelegate
//微信语音识别结果 调用js方法recognition返给后台
-(void)wXSpeech:(WXSpeech *)wXSpeech wXInfo:(NSString *)info{
    
    if (info) {
//        NSDictionary*dic =@{@"msg":info};
        // 调用JS中的API
        [self.bridge callHandler:@"pronunciation" data:info responseCallback:^(id responseData) {
            
        }];
    }
    
    
}

#pragma mark--AVAudioDelegate
//录音调用接口 直接jsn返给后台
-(void)aVAudio:(AVAudio *)aVAudio aVAudioInfo:(NSDictionary *)info{
    
    // 调用JS中的API
    [self.bridge callHandler:@"recognition" data:info responseCallback:^(id responseData) {
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
